"""
Pytest配置文件
"""
import os
import pytest
import allure
from datetime import datetime

from ..utils.http_client import HttpClient
from ..utils.logger import logger

@pytest.fixture(scope="session")
def http_client():
    """
    HTTP客户端夹具
    
    Returns:
        HttpClient实例
    """
    client = HttpClient()
    logger.info(f"创建HTTP客户端，基础URL: {client.base_url}")
    return client

@pytest.fixture(scope="function", autouse=True)
def log_test_info(request):
    """
    自动记录测试信息的夹具
    
    Args:
        request: pytest请求对象
    """
    test_name = request.node.name
    logger.info(f"开始测试: {test_name}")
    
    # 记录测试开始时间
    start_time = datetime.now()
    
    # 在Allure报告中添加测试信息
    allure.dynamic.description(f"测试开始时间: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    yield
    
    # 记录测试结束时间和耗时
    end_time = datetime.now()
    duration = (end_time - start_time).total_seconds()
    logger.info(f"测试完成: {test_name}, 耗时: {duration:.2f}秒")
    
    # 在Allure报告中添加测试结束信息
    allure.dynamic.description_html(
        f"<p>测试开始时间: {start_time.strftime('%Y-%m-%d %H:%M:%S')}</p>"
        f"<p>测试结束时间: {end_time.strftime('%Y-%m-%d %H:%M:%S')}</p>"
        f"<p>测试耗时: {duration:.2f}秒</p>"
    )

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """
    测试结果处理钩子
    
    Args:
        item: 测试项
        call: 测试调用
    """
    outcome = yield
    report = outcome.get_result()
    
    if report.when == "call":
        if report.failed:
            logger.error(f"测试失败: {item.name}")
            # 在失败时添加额外信息到Allure报告
            if call.excinfo:
                allure.attach(
                    str(call.excinfo),
                    name="异常信息",
                    attachment_type=allure.attachment_type.TEXT
                )
        elif report.passed:
            logger.info(f"测试通过: {item.name}")

@pytest.fixture(scope="session")
def env_info():
    """
    环境信息夹具
    
    Returns:
        环境信息字典
    """
    env_info = {
        "Python版本": os.popen("python --version").read().strip(),
        "操作系统": os.popen("uname -a" if os.name != "nt" else "ver").read().strip(),
        "测试环境": os.getenv("ENV", "dev"),
        "测试时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    
    # 将环境信息添加到Allure报告
    for key, value in env_info.items():
        allure.dynamic.parameter(key, value)
    
    return env_info 